import React from 'react';
import { connect } from 'dva';
import { Form, Row, Col, Button, Dropdown, Menu, Icon, Badge } from 'antd';
import { AxReactHTMLTableToExcel } from '@/components/AxBase';

/**
 * 自定义查询表单
 * @param items 表单项
 * @param advanceSearch 高级查询
 * @param handleSearch 查询处理函数
 */
@connect(({ global, loading }) => ({
  modelState: global, // 将实体listTableList中的state数据绑定到props
  loading: loading.models.global,
}))
class AxSimpleSearch extends React.Component {
  constructor(props) {
    super(props);
  }

  handleSubmit = e => {
    const { form, handleSearch } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (handleSearch) {
        for (const p in fieldsValue) {
          const v = fieldsValue[p];
          /** 去掉空格 */
          if (v && v.trim) {
            fieldsValue[p] = v.trim();
          }
          /** 处理提交的时间格式 */
          if (
            p.toLowerCase().indexOf('time') > -1 ||
            p.toLowerCase().indexOf('created') > -1 ||
            p.toLowerCase().indexOf('date') > -1
          ) {
            if (v && v.length === 2 && v[0].format && v[1].format) {
              fieldsValue[p] = v[0].format(v._f) + '~' + v[1].format(v._f);
              fieldsValue[p + 'Start'] = v[0].format(v._f);
              fieldsValue[p + 'End'] = v[1].format(v._f);
            } else if (v && v.format && v._f) {
              fieldsValue[p] = v.format(v._f);
            }
          }
        }
        handleSearch(e, fieldsValue);
      }
    });
  };

  handleResetSearch = () => {
    const { handleResetSearch } = this.props;
    if (handleResetSearch) handleResetSearch('read');
  };

  handleSubmitClick = () => {
    this.btnRef.click();
  }

  render() {
    const {
      form,
      items,
      advanceSearch = true,
      handleVisible,
      handleResetSearch,
      searchFormValues = [],
      modelState: { clientWidth },
      ioButtons = [],
      exportButton,
    } = this.props;

    /** 计算查询条件的数量 */
    let searchFormValuesLength = 0;
    if (searchFormValues) {
      for (let k in searchFormValues) {
        if (
          searchFormValues[k] === undefined ||
          searchFormValues[k] === null ||
          searchFormValues[k] === '' ||
          (Array.isArray(searchFormValues[k]) && searchFormValues[k].length === 0)
        )
          continue;
        searchFormValuesLength++;
      }
    }
    /** 时间范围查询，算一个查询数量 */
    const reg = new RegExp(/^\w+Start$/);
    const keys = Object.keys(searchFormValues);
    keys.forEach(k => {
      if (reg.test(k)) {
        const field = k.substr(0, k.length - 5);
        if (keys.findIndex(f => f === field) > -1 && keys.findIndex(f => f === (field + 'End')) > -1) {
          searchFormValuesLength -= 2;
        }
      }
    })

    let groupAdvancedSearch = false;
    let groupIo = false;
    /** 控制按钮的折叠功能，有【高级查询】和【导入导出】 */
    if (advanceSearch || ioButtons.length > 0 || exportButton || clientWidth !== 0) {
      /** 只有【高级查询】 */
      if (advanceSearch && ioButtons.length === 0 && !exportButton) {
        if (clientWidth <= 888) {
          groupAdvancedSearch = true;
        }
        else {
          groupAdvancedSearch = false;
        }
      }
      else if (!advanceSearch && ioButtons.length > 0 || exportButton) { //只有【导入导出】
        if (clientWidth <= 950) {
          groupIo = true;
        }
        else {
          groupIo = false;
        }
      }
      else if (advanceSearch && (ioButtons.length > 0 || exportButton)) {//都有
        if (clientWidth <= 1100) {
          groupIo = true;
          groupAdvancedSearch = true;
        }
        else if (clientWidth <= 1448) {
          groupIo = true;
          groupAdvancedSearch = false;
        }
        else {
          groupAdvancedSearch = false;
          groupIo = false;
        }
      }
    }
    else {
      groupAdvancedSearch = false;
      groupIo = false;
    }

    const handleMore = (key, items) => {
      switch (key) {
        case 'search':
          this.handleSubmitClick();
          break;
        case 'advancedSearch':
          handleVisible && handleVisible(true);
          break;
        case 'resetSearch':
          this.handleResetSearch();
          break;
        case 'react-html-table-to-excel-item':
          break;
        default:
          const item = items[key];
          item && item.onClick && item.onClick();
      }
    };

    const getIoBtn = ({ items }) => (
      <Dropdown
        trigger={['click']}
        overlay={
          <Menu onClick={({ key }) => handleMore(key, items)}>
            {items.map((i, idx) => (
              <Menu.Item key={idx} disabled={i.disabled} hidden={i.hidden}>
                <Icon type={i.icon} />
                {i.text}
              </Menu.Item>
            ))}
            {exportButton && (
              <Menu.Item key="react-html-table-to-excel-item">
                <Icon type={exportButton.icon || 'export'} />
                <AxReactHTMLTableToExcel
                  key="key-react-html-table-to-excel"
                  className="ant-btn ant-btn-primary"
                  table={exportButton.exportId || 'table-to-xls'}
                  filename={exportButton.filename || '文件名称'}
                  sheet={exportButton.sheet || 'Sheet1'}
                  buttonText={exportButton.text || '导出'}
                />
              </Menu.Item>
            )}
          </Menu>
        }
      >
        <Button
          size={window.ax.config.size}
          type="primary"
          style={{ marginRight: 0, marginLeft: 4 }}
        >
          导入导出 <Icon type="down" />
        </Button>
      </Dropdown>
    );

    return items && items.length > 0 ? (
      <Form onSubmit={e => this.handleSubmit(e)}>
        <Row type="flex" justify="end" gutter={8}>
          {items.map((i, index) => (
            <Col key={index} span={6}>
              {form.getFieldDecorator(i.props.field, {
                initialValue: i.props.axvalue,
              })(i)}
            </Col>
          ))}
          {/* 显示按钮 */}
          <>
            {/* 查询 */}
            <Col key={4} style={{ width: '40px' }}>
              <Button
                size={window.ax.config.size}
                type="primary"
                icon="search"
                style={{ width: '100%' }}
                htmlType="submit"
              />
            </Col>
            {/* 高级查询 */}
            {!groupAdvancedSearch && advanceSearch && (
              <Col key={5}>
                {handleResetSearch && searchFormValuesLength > 0 ? (
                  <Badge count={searchFormValuesLength}>
                    <Dropdown
                      trigger={['hover']}
                      overlay={
                        <Menu>
                          <Menu.Item
                            key={0}
                            style={{ textAlign: 'center' }}
                            onClick={this.handleResetSearch}
                          >
                            重置查询
                        </Menu.Item>
                        </Menu>
                      }
                    >
                      <Button
                        size={window.ax.config.size}
                        type="primary"
                        style={{ width: '100%' }}
                        onClick={() => handleVisible && handleVisible(true)}
                      >
                        高级查询
                      <Icon type="down" />
                      </Button>
                    </Dropdown>
                  </Badge>
                ) : (
                    <Badge count={searchFormValuesLength}>
                      <Button
                        size={window.ax.config.size}
                        type="primary"
                        style={{ width: '100%' }}
                        onClick={() => handleVisible && handleVisible(true)}
                      >
                        高级查询
                        </Button>
                    </Badge>
                  )}
              </Col>
            )}
            {!groupIo && ((ioButtons && ioButtons.length > 0) || exportButton) && (<Col key={6}>{getIoBtn({ items: ioButtons })}</Col>)}
            {/* 折叠按钮 */}
            {(groupAdvancedSearch || groupIo) && <Col key={7}><>
              <button
                ref={r => this.btnRef = r}
                style={{ width: '100%', display: "none" }}
                type="submit"
              />
              <Dropdown
                trigger={['click']}
                overlay={
                  <Menu onClick={({ key }) => handleMore(key, ioButtons)}>
                    {/* <Menu.Item key='search'>
                    <Icon type='search' />
                    搜索
                  </Menu.Item> */}
                    {groupAdvancedSearch && advanceSearch && <Menu.Item key='advancedSearch'>
                      <Badge count={searchFormValuesLength}>
                        <Icon type='search' />
                      高级查询
                    </Badge>
                    </Menu.Item>}
                    {groupAdvancedSearch && handleResetSearch && searchFormValuesLength > 0 && <Menu.Item key='resetSearch'>
                      <Icon type='redo' />
                      重置查询
                  </Menu.Item>}
                    {groupIo && ioButtons.map((i, idx) => (
                      <Menu.Item key={idx} disabled={i.disabled} hidden={i.hidden}>
                        <Icon type={i.icon} />
                        {i.text}
                      </Menu.Item>
                    ))}
                    {exportButton && (
                      <Menu.Item key="react-html-table-to-excel-item">
                        <Icon type={exportButton.icon || 'export'} />
                        <AxReactHTMLTableToExcel
                          key="key-react-html-table-to-excel"
                          className="ant-btn ant-btn-primary"
                          table={exportButton.exportId || 'table-to-xls'}
                          filename={exportButton.filename || '文件名称'}
                          sheet={exportButton.sheet || 'Sheet1'}
                          buttonText={exportButton.text || '导出'}
                        />
                      </Menu.Item>
                    )}
                  </Menu>
                }
              >
                <Button
                  size={window.ax.config.size}
                  style={{ marginRight: 0 }}
                  type="primary"
                >
                  <Icon type="more" />
                </Button>
              </Dropdown>
            </>
            </Col>}
          </>
        </Row >
      </Form >
    ) : null;
  }
}

export default Form.create()(AxSimpleSearch);
